package cjq.demo.geetest;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * author: cjianquan
 * date: 2017/2/13
 */
public class GeetestDemo {

    /**
     * 合成指定的多张图片到一张图片
     *
     * @param imgSrcList       图片的地址列表
     * @param topLeftPointList 每张小图片的偏移量
     * @param countOfLine 每行的小图片个数
     * @param cutWidth         每张小图片截取的宽度（像素）
     * @param cutHeight        每张小图片截取的高度（像素）
     * @param savePath         合并后图片的保存路径
     * @param subfix         合并后图片的后缀
     * @return 是否合并成功
     */
    public static boolean combineImages(String imgSrc, List<String[]> topLeftPointList, int countOfLine, int cutWidth, int cutHeight, String savePath, String subfix) {
        if (imgSrc == null || savePath == null || savePath.trim().length() == 0) return false;


        String src = imgSrc;
        BufferedImage image=null;

        try{
            if (src.trim().toLowerCase().startsWith("http")){
                InputStream inputStream = getStreamFromUrl(imgSrc);
                image = ImageIO.read(inputStream);
            }
            else{
                image = ImageIO.read(new File(src));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(image==null){
            return false;
        }

        BufferedImage lastImage = new BufferedImage(cutWidth * countOfLine, cutHeight * ((int) (Math.floor(topLeftPointList.size() / countOfLine))), BufferedImage.TYPE_INT_RGB);
//        saveToFile(imgSrc);
//        String imgSrcPath = "E:\\ideaWorkspace\\test\\geetest02.webp";
        try {
            for (int i = 0; i < topLeftPointList.size(); i++) {

                String[] topLeftPoint = topLeftPointList.get(i);
                int[] pixArray = image.getRGB(Integer.parseInt(topLeftPoint[0].trim()), Integer.parseInt(topLeftPoint[1].trim()), cutWidth, cutHeight, null, 0, cutWidth);
                int startX = ((i) % countOfLine) * cutWidth;
                int startY = ((i) / countOfLine) * cutHeight;

                lastImage.setRGB(startX, startY, cutWidth, cutHeight, pixArray, 0, cutWidth);
            }
            File file = new File(savePath);
            return ImageIO.write(lastImage, subfix, file);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }


    public static InputStream getStreamFromUrl(String destUrl){
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
        } catch (IOException e) {
        } catch (ClassCastException e) {
        } finally {
            try {
//                bis.close();
                httpUrl.disconnect();
            } catch (Exception e) {
            }
        }
        return bis;
    }

    public static void saveToFile(String destUrl) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            fos = new FileOutputStream("E:\\ideaWorkspace\\test\\geetest111.jpg");
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
        } catch (IOException e) {
        } catch (ClassCastException e) {
        } finally {
            try {
                fos.close();
                bis.close();
                httpUrl.disconnect();
            } catch (IOException e) {
            } catch (NullPointerException e) {
            }
        }
    }


}
